package com.eslserver.action.dropdown;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.aware.ScheduleAware;
import com.eslserver.dao.DAOException;
import com.eslserver.dao.ESLDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.dao.ScheduleDAO;
import com.eslserver.to.ESL;
import com.eslserver.to.Schedule;
import com.eslserver.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class ESLDropdownServlet extends HttpServlet implements ScheduleAware {
	public static final Logger LOG = LoggerFactory
			.getLogger(ESLDropdownServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();

		try {
			ScheduleDAO scheduleDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getScheduleDAO();
			ESLDAO eslDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getESLDAO();

			String scheduleID = req.getParameter(PARAM_SCHEDULE_ID);
			Integer eslID = 0;
			if (scheduleID != null && scheduleID.length() > 0) {
				if (Integer.valueOf(scheduleID) != 0) {
					Schedule schedule = scheduleDAO.loadSchedule(Integer
							.valueOf(scheduleID));
					eslID = schedule != null ? schedule.getEsl().getESLID()
							: eslID;
				}
			}

			Map<Integer, String> eslMap = new HashMap<Integer, String>();

			for (ESL esl : eslDAO.loadAllESLs()) {
				eslMap.put(esl.getESLID(), esl.getName());
			}

			writer.println(JSONResponseUtil
					.getJSONObjectString(new ESLDropdownWrapper(eslMap, eslID)));

		} catch (DAOException e) {
			LOG.error("error laoding ESLs", e);
		}

	}

	private class ESLDropdownWrapper {
		Map<Integer, String> eslMap;
		Integer eslID;

		public ESLDropdownWrapper(Map<Integer, String> eslMap, Integer eslID) {
			this.eslMap = eslMap;
			this.eslID = eslID;
		}
	}
}
